package com.simplenix.nicasio.def;

import com.simplenix.nicasio.misc.AppException;
import com.simplenix.nicasio.misc.Internationalization;
import com.simplenix.nicasio.misc.StrUtil;
import com.simplenix.nicasio.misc.XMLUtil;
import com.simplenix.nicasio.sys.SystemDef;
import java.io.File;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;

/**
 *
 * @author fronald
 */
public class Features {

	List<Feature> features;

	public Features(Module module) throws AppException {
		this.features = new ArrayList<Feature>();
		if (!module.getName().equals("nicasio")) {
			try {
				Document featuresXml = XMLUtil.fileToXml(new File(SystemDef.getInstance().getAppPath() + "/WEB-INF/config/features-" + module.getName() + ".xml"));
				Element root = featuresXml.getRootElement();
				List<Element> elements = root.elements();
				for (Element feat : elements) {
					Feature feature = new Feature();
					String name = StrUtil.nvl(feat.attributeValue("name"));
					String tab = StrUtil.nvl(feat.attributeValue("tab"));
					String description = StrUtil.nvl(feat.attributeValue("descriptionString"));
					if (!name.equals("") && !description.equals("") && !tab.equals("")) {
						feature.setDescription(Internationalization.getInstance().getString(description));
						feature.setName(name);
						feature.setTab(tab);
						this.features.add(feature);
					}
				}
			} catch (MalformedURLException e) {
				throw new AppException("Malformed URL!", e);
			} catch (DocumentException e) {
				throw new AppException("Malformed XML!", e);
			}
		} else {
			Feature portal = new Feature();
			portal.setName("portal");
			portal.setTab("home");
			portal.setDescription("Application home page");
			this.features.add(portal);
		}
	}

	public List<Feature> getFeatureList() {
		return new ArrayList<Feature>(this.features);
	}

	public Feature getFeatureByName(String featName) {
		for (Feature feature : this.features) {
			if (feature.getName().equals(featName)) {
				return feature;
			}
		}
		return null;
	}

}
